'''
Created on Aug 17, 2012

@author: petrina
'''
from link_indicator import Link_indicator
from indiutils import Indiutils
import logging
 

class Buffer_index(Link_indicator):
    '''
    Calculates the buffer index for every time interval (using aggregated fcd-data).
    
    Formula for calculating the index: 
        bi_i = (wtt_i - att_i)*100 /att_i
            where:
                - bi_i... Buffer-Index for time interval i
                - wtt ... Worst-case-traveltime  for time interval i
                - att ... average-travel time for time interval i
                
    As worst-case-traveltime the 95th percentile travel time is chosen.
    
    unit: percent (%)
    '''


    def __init__(self, link):
        '''        
        @param link: Link-object (containing valid records and timeseries) 
        '''
        
        Link_indicator.__init__(self, link)
        self._name = 'Buffer Index'
        self._mr_name =  'buffer_idx'
        self._unit = '%'
        #self.unit.__doc__ = 'percent (%)'
        self._create_title(link.id, link.direction)
        
        #print self._name, self._mr_name
        
        logging.debug("Buffer_index: created new Buffer_index")
        
    #----------------------public methods of the class-------------------------

    def calculate(self):
        '''
        @return: buffer index for every time interval as list of Result_values
        '''
        
        logging.info("Buffer_index: starting to calculate the buffer index")
        
        utils = Indiutils()
        p95 = utils.p95_tt(self._link.timeseries, self._link.length)
        att = utils.calc_average_of(self._link.records, "traveltime")
        self._values = []
      
        # build the buffer index for every time interval
        for i in range(self._intervals):
            # treat empty lists (= no measurement) or dev/0
            value = (p95[i] - att[i]) * 100/att[i] if p95[i] is not None and att[i] is not None and att[i] != 0 else None
            self._values.append(value)
        
        logging.debug("Buffer_index: finished calculating the buffer index")

        return self._values